<?php

namespace App\Console\Commands\Cron;

use App\Models\Chat;
use App\Models\Live;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class SaveChat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cron:save-chat';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '保存聊天信息';

    public function handle()
    {
//        $this->info(Redis::lLen('chat'));
        $j = Redis::lLen('chat');
        for ($i = 0; $i < $j; $i ++) {
            if ($res = Redis::lPop('chat')) {
                $res = json_decode($res,true);
                $chat = new Chat([
                    'sequence' => intval($res['sequence']),
                    'type' => $res['type'],
                    'send_time' => $res['send_time'],
                    'content' => $res['content']
                ]);

                try {
                    $chat->user()->associate($res['user_id']);
                    $chat->live()->associate($res['live_id']);
                } catch (\Exception $e) {
                    continue;
                }

                $chat->save();
            }
        }
    }
}
